import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
//import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/baoxiu/brandselect.dart';
import 'package:magic_car/baoxiu/cartype.dart';
import 'package:magic_car/baoxiu/insurance.dart';
import 'package:magic_car/jiance/inspectresults.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:toast/toast.dart';
import 'dart:io';
// import 'package:date_format/date_format.dart';
import 'package:magic_car/UI/mykeyboard.dart' as board;
// import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

//检测页面重写
class Papularinspects extends StatefulWidget {
  //final Map param;
  final String oid;
  final int type;
  final Map picParam;
  Papularinspects(this.oid, this.type, this.picParam);

  @override
  _MyHomePageState createState() =>
      new _MyHomePageState(this.oid, this.type, this.picParam);
}

class _MyHomePageState extends State<Papularinspects> {
  GlobalKey _globalKey;
  List<Offset> _points = <Offset>[];
  List formList;
  //final Map param;
  final String oid;
  final int type;
  final Map picParam;
  _MyHomePageState(this.oid, this.type, this.picParam);
  bool select = false;
  String itemid;
  bool resize = false; //是否收起按钮
  Map _cityNames;

  Map param;
  List testItem;

  Map picinspect = new Map();
  bool loaddata = false;
  String status;
  Map formalities;
  Map oldformalities;

  Map cartbrand = new Map();
  Map cartype = new Map();

  Map orderInfo;
  // FlutterBlue flutterBlue = FlutterBlue.instance;
  // BluetoothDevice device;
  bool showUrl = false;

  String pwdData = '输入车牌';

  Color Select_Color;

  int line_Height1 = 1;
  Color line_color1 = Colors.red;

  int line_Height2 = 1;
  Color line_color2 = Colors.red;

  int line_Height3 = 1;
  Color line_color3 = Colors.red;

  String Checkresult = '';
  bool connectBluetooth = false;

  // FlutterBlue flutterBlue = FlutterBlue.instance;
  // BluetoothDevice device;
  Map currentTest = new Map();
  int selectIndex;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  ScrollController scrollController = new ScrollController();
  TextEditingController buchongControll = new TextEditingController();
  // VoidCallback：没有参数并且不返回数据的回调
  VoidCallback _showBottomSheetCallback;

  AppBar appBar = AppBar(
    title: new Text('检测'),
    backgroundColor: Colors.white,
    iconTheme: new IconThemeData(color: Colors.black),
    elevation: 0,
    // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
  );
  initState() {
    super.initState();
    _globalKey = GlobalKey();
    _showBottomSheetCallback = _showBottomSheet;
    formList = [
      {
        "title": '购车发票/过户票',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "value": "有",
        "code": "invoice"
      },
      {
        "title": '购置税证',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "Tax",
        "value": "有"
      },
      {
        "title": '行驶证',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "vehicle",
        "value": "有"
      },
      {
        "title": '年检有效期',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "1",
        "code": "yearcheck_e_time",
        "value": "请选择日期"
      },
      {
        "title": '登记证',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "registration",
        "value": "有"
      },
      {
        "title": '过户次数',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "transfer",
        "value": ""
      },
      {
        "title": '交强险有效期',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "1",
        "code": "compu_e_time",
        "value": "请选择日期"
      },
      {
        "title": '交强险保险公司',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "4",
        "code": "compu_name",
        "value": "请选择交强险保险公司"
      },
      {
        "title": '车船税有效期',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "1",
        "code": "vehicles_e_time",
        "value": "请选择日期"
      },
      // {
      //   "title": '车船险随车出售',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': "3",
      //   "code": "vehicles",
      //   "value": "是"
      // },
      {
        "title": '商业险金额',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "business_price",
        "value": ""
      },
      {
        "title": '商业险保险公司',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "4",
        "code": "business_name",
        "value": "请选择商业险保险公司"
      },
    ];
    _cityNames = {
      '北京': ['东城区', '西城区'],
      '郑州': ['高新区', '金水区'],
      '上海': ['黄浦区', '徐汇区'],
      '杭州': ['西湖区', '滨江区'],
    };
    formalities = {
      "invoice": '', //购车发票/过户票
      "Tax": '', //购置税证
      "vehicle": '', //行驶证
      "vehicles_b_time": '', //年检有效期开始时间
      "yearcheck_e_time": '', //年检有效期结束时间
      "registration": '', //登记证
      "transfer": '', //过户次数
      "compu_b_time": '', //交强险有效期 begin
      "compu_e_time": '', //交强险有效期 end
      "compu_name": '', //交强险保险公司
      "vehicles_b_time": '', //车船税有效期 start
      "vehicles_e_time": '', //车船税有效期 end
      "business_b_time": '', // 商业保险有效期 start
      "business_e_time": '', //商业保险有效期  end
      "business_sell_by_car": false, //商业险随车出售
      "business_price": '', //商业险金额
      "business_name": '', //商业保险公司
      "nameplate": '', //车身铭牌
      "busines": '', //是否有商业险
      "compu": '', //是否有交强险
      "vehicles": '', //车船税是否
      "compu_name1": '',
      "business_name": ''
    };
    cartbrand = {'value': '选择品牌', 'brand_id': ''};
    cartype = {'value': '选择车系', 'type_id': ''};
    loaddetail();
    //showAlert();
  }

// //重写蓝牙模块
//   scan() async {
//     flutterBlue.scan().listen((scanResult) async {
//       // do something with scan result
//       device = scanResult.device;

//       if (device.name.startsWith('LS')) {
//         Toast.show('漆膜仪连接成功', context);
//         setState(() {
//           connectBluetooth = true;
//         });
//         print('找到指定设备。');

//         await device.connect();
//         device = device;
//         flutterBlue.stopScan();
//         List<BluetoothService> services = await device.discoverServices();
//         services.forEach((service) async {
//           // do something with service
//           var characteristics = service.characteristics;
//           for (BluetoothCharacteristic c in characteristics) {
//             // List<int> value = await c.read();
//             // print(value);
//             await c.setNotifyValue(true);
//             c.value.listen((value) {
//               print('值发生改变');
//               Toast.show('值发生改变', context);
//               print(value is List);
//               print(value);
//               //print(value.length);
//               if (value.length > 0) {
//                 //第一位先转换为16进制
//                 print(value[8].toRadixString(16).toUpperCase());
//                 var hexStr = "";
//                 if (value[9] == 255) {
//                   //负数
//                 } else {
//                   if (value[8] < 10) {
//                     hexStr = '0' +
//                         value[11].toString() +
//                         '0' +
//                         value[10].toString() +
//                         '0' +
//                         value[9].toString() +
//                         '0' +
//                         value[8].toString();
//                   } else {
//                     var str = value[8].toRadixString(16).toUpperCase();
//                     if (str.length == 1) {
//                       str = "0" + str;
//                     }
//                     hexStr = '0' +
//                         value[11].toString() +
//                         '0' +
//                         value[10].toString() +
//                         '0' +
//                         value[9].toString() +
//                         str;
//                   }
//                   print(hexStr);
//                   print('转换结果' + _hexToInt(hexStr).toString());
//                   Toast.show(_hexToInt(hexStr).toString(), context);
//                   if (currentTest.containsKey('numerical_value')) {
//                     //有这个检测结果数组，从里面添加
//                     // if(currentTest)
//                     List tempArr = currentTest['numerical_value'];
//                     if (tempArr.length == int.parse(currentTest['testnum'])) {
//                       //达到数量之后开始校验数组

//                       Toast.show('此项测量数量达上线，请进行下一项检测', context);
//                       tempArr.sort();
//                       double re = tempArr.last;
//                       List tempList = currentTest['item'].split(',');
//                       if (re <= 180) {
//                         currentTest["value"] = tempList[0];
//                       } else if (re <= 330) {
//                         currentTest["value"] = tempList[1];
//                       } else if (re > 330) {
//                         currentTest["value"] = tempList[2];
//                       }
//                       setState(() {
//                         currentTest = currentTest;
//                       });
//                       print(tempArr.last);
//                       return;
//                     }
//                     double re = _hexToInt(hexStr) / 10;
//                     // if(re>100){
//                     //   print('需要社区小数点');
//                     //   tempArr.add(int.parse(re.toString()));
//                     // }else
//                     tempArr.add(_hexToInt(hexStr) / 10);
//                   } else {
//                     currentTest['numerical_value'] = [];
//                     currentTest['numerical_value'].add(_hexToInt(hexStr) / 10);
//                   }
//                   print(currentTest);
//                   setState(() {
//                     currentTest = currentTest;
//                   });
//                 }
//               }
//               // do something with new value
//             });
//           }
//         });
//         //flutterBlue.stopScan();
//       }
//       print('${device.name} found! rssi: ${scanResult.rssi}');
//     });

//     /// 关闭扫描操作，避免内存泄漏
//   }

// //漆膜仪连接
//   connect() async {
//     LoadingPage loadpage = new LoadingPage(context);
//     loadpage.show();

//     flutterBlue.scan().listen((scanresult) {
//       print('蓝牙名称' + scanresult.device.name);
//       String deveceName = scanresult.device.name;
//       if (deveceName.startsWith('LS')) {
//         print('zhaodao');
//         loadpage.close();
//         Future.delayed(Duration(seconds: 0), () {
//           showAlerts(deveceName);
//           print('延时1s执行');
//         });

//         device = scanresult.device;

//         flutterBlue.stopScan();
//       } else {
//         //Toast.show('正在重新扫描设备', context);
//       }
//     });

//     //}
//   }

  showAlerts(texts) {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('找到设备,是否连接？'),
            content: new Text(texts),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context, rootNavigator: true).pop();
                    // Navigator.pop(context);
                  },
                  child:
                      new Text('否', style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context, rootNavigator: true).pop();
                   // startconnetc();
                    // Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }

  // startconnetc() async {
  //   await device.connect();
  //   Toast.show('漆膜仪连接成功', context);
  //   setState(() {
  //     connectBluetooth = true;
  //   });

  //   List<BluetoothService> services = await device.discoverServices();
  //   services.forEach((service) async {
  //     // do something with service
  //     var characteristics = service.characteristics;
  //     for (BluetoothCharacteristic c in characteristics) {
  //       // List<int> value = await c.read();
  //       // print(value);
  //       if (c.uuid.toString() == "0000ffe1-0000-1000-8000-00805f9b34fb") {
  //         await c.setNotifyValue(true);
  //         c.value.listen((value) {
  //           print('值发生改变');
  //           // Toast.show('值发生改变', context);
  //           print(value is List);
  //           print(value);
  //           //print(value.length);
  //           if (value.length > 0) {
  //             //第一位先转换为16进制
  //             //  print(value[8].toRadixString(16).toUpperCase());
  //             var hexStr = "";
  //             if (value[9] == 255) {
  //               //负数
  //             } else {
  //               if (value[8] < 10) {
  //                 hexStr = '0' +
  //                     value[11].toString() +
  //                     '0' +
  //                     value[10].toString() +
  //                     '0' +
  //                     value[9].toString() +
  //                     '0' +
  //                     value[8].toString();
  //               } else {
  //                 var str = value[8].toRadixString(16).toUpperCase();
  //                 if (str.length == 1) {
  //                   str = "0" + str;
  //                 }
  //                 hexStr = '0' +
  //                     value[11].toString() +
  //                     '0' +
  //                     value[10].toString() +
  //                     '0' +
  //                     value[9].toString() +
  //                     str;
  //               }
  //               print(hexStr);
  //               print('转换结果' + _hexToInt(hexStr).toString());
  //               // Toast.show(_hexToInt(hexStr).toString(), context);
  //               if (currentTest.containsKey('numerical_value')) {
  //                 //有这个检测结果数组，从里面添加
  //                 // if(currentTest)
  //                 List tempArr = currentTest['numerical_value'];
  //                 if (tempArr.length == int.parse(currentTest['testnum'])) {
  //                   //达到数量之后开���校验数组

  //                   Toast.show('此项测量数量��上线，请进行下一项检测', context);
  //                   tempArr.sort();
  //                   double re = tempArr.last;
  //                   List tempList = currentTest['item'].split(',');
  //                   if (re <= 180) {
  //                     currentTest["value"] = tempList[0];
  //                   } else if (re <= 330) {
  //                     currentTest["value"] = tempList[1];
  //                   } else if (re > 330) {
  //                     currentTest["value"] = tempList[2];
  //                   }
  //                   setState(() {
  //                     currentTest = currentTest;
  //                   });
  //                   print(tempArr.last);
  //                   return;
  //                 }
  //                 double re = _hexToInt(hexStr) / 10;
  //                 // if(re>100){
  //                 //   print('需要社区小数点');
  //                 //   tempArr.add(int.parse(re.toString()));
  //                 // }else
  //                 tempArr.add(_hexToInt(hexStr) / 10);
  //               } else {
  //                 currentTest['numerical_value'] = [];
  //                 currentTest['numerical_value'].add(_hexToInt(hexStr) / 10);
  //               }
  //               print(currentTest);
  //               setState(() {
  //                 currentTest = currentTest;
  //               });
  //             }
  //           }
  //           // do something with new value
  //         });
  //       }
  //     }
  //   });
  // }

  // showAlert() {
  //   showDialog(
  //     context: context,
  //     builder: (BuildContext context) {
  //       return new AlertDialog(
  //           title: Text('提示!'),
  //           content: new Text('是否连接漆膜仪检测?'),
  //           actions: <Widget>[
  //             new FlatButton(
  //                 onPressed: () {
  //                   Navigator.of(context, rootNavigator: true).pop();
  //                 },
  //                 child:
  //                     new Text('否', style: new TextStyle(color: Colors.red))),
  //             new FlatButton(
  //                 onPressed: () {
  //                   Navigator.of(context, rootNavigator: true).pop();
  //                   connect();
  //                   // scan();

  //                   // Navigator.pop(context);
  //                 },
  //                 child: new Text(
  //                   '是',
  //                   style: new TextStyle(color: Colors.black),
  //                 ))
  //           ]);
  //     },
  //   );
  // }

  loaddetail() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    String api = HttpHelper.API_OrderDetail;
    if (this.type == 2) {
      api = HttpHelper.API_BussinessOrderDetail;
    }
    print(map);
    HttpHelper.post(api, (data) async {
      Future.delayed(Duration(seconds: 2), () {
        // connect();
       // showAlert();
        print('延时1s执行');
      });
      if (data != null) {
        if (data["code"].toString() == "1") {
          setState(() {
            status = data["info"]["status"].toString();
            orderInfo = data["info"];
          });
          if (data["info"]["status"] != "0" && data["info"]["status"] != "1") {
            setState(() {
              testItem = data["info"]["inspectorItemsResult"]["otherData"]
                  ["checkData"];
              oldformalities =
                  data["info"]["inspectorItemsResult"]["formalities"];
              loaddata = true;
              status = data["info"]["status"].toString();
            });

            Map foemlitile =
                data["info"]["inspectorItemsResult"]["formalities"];

            var templist = formList;
            print('数据重组');
            print(foemlitile);
            for (var i = 0; i < formList.length; i++) {
              var code = formList[i]["code"];
              print(code);

              templist[i]["value"] = foemlitile[code];
              if (code == "vehicles") {
                if (foemlitile[code] == true) {
                  formList[i]["value"] = "是";
                } else {
                  formList[i]["value"] = "否";
                }
              }
              if (code == "business_sell_by_car") {
                if (foemlitile[code] == true) {
                  formList[i]["value"] = "是";
                } else {
                  formList[i]["value"] = "否";
                }
              }
            }
            setState(() {
              formList = templist;
            });
            print(formList);
            // if (data["info"]["inspectorItemsResult"] != null) {
            // if (type == 1) {
            //   setState(() {
            //     testItem = data["info"]["inspectorItemsResult"]["otherData"]
            //         ["checkData"];
            //     loaddata = true;
            //     status = data["info"]["status"].toString();
            //   });
            // }else{
            //   setState(() {

            //     loaddata = true;
            //     status = data["info"]["status"].toString();
            //   });
            // }
          } else {
            print('获取系统检测项');
            loadTestItem(data["info"]["test_type"]);
            var templist = formList;
            var listvalue = this.formalities;
            print(this.formalities);
            for (var i = 0; i < formList.length; i++) {
              var code = formList[i]["code"];
              print(code);
              print(this.formalities[code]);

              // this.formalities[code]=formList[i]["value"];
              formList[i]["value"] = this.formalities[code] == ""
                  ? formList[i]["value"]
                  : this.formalities[code];
            }
            setState(() {
              formList = formList;
            });
            print(formList);
          }
          // List oldlist = formList;
          // var orderinfo = data["info"];
          // for(var i =0;i<oldlist.length;i++){
          //   var item = oldlist[i];
          //   var str = "";
          //   if(i==0) str = orderinfo["name"];
          //   else if(i==1) str = orderinfo["phone_num"];
          //   else if(i==2) str = orderinfo["name"];
          //   else if(i==3) str = orderinfo["phone_num"];
          //   else if(i==4) str = orderinfo["add_time"];
          //   else str = orderinfo["address"];

          //   item["sub_title"]=str;
          // }

          setState(() {
            //formList = oldlist;
            // orders=data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  //加载检测项
  loadTestItem(type) {
    print('加载检测项');
    var types = 1;
    if (type == "事故检测")
      types = 2;
    else if (type == "保修检测") types = 3;
    Map<String, String> map = new Map();
    map["type"] = types.toString();
    HttpHelper.post(HttpHelper.API_LoadTestItem, (data) async {
      print('系统检测项');
      print(data);

      if (data != null) {
        for (var v in data) {
          v['temp_mustimg'] = '0';
          for (var k in v["post"]) {
            if (k["id"] == "3029") {
              if (this.type == 1) {
                k["value"] = "11111";
                //  k["value"]=orderInfo['carmsg']["plate_number"];
              } else {
                k["value"] = orderInfo["car_num"];
              }
            } else if (k["id"] == "3035") {
              k["value"] = orderInfo["brand_string"]['name'] +
                  '/' +
                  orderInfo["cartype_string"]['name'];
            }
          }

          if (v['id'] == '4000') {
            //照片和检测项分开

            v['post'].add(picParam); //增加人车合照
            print(picParam);
            print('人车合照');
          }
        }
        setState(() {
          testItem = data;
          loaddata = true;
        });
      }
    }, params: map);
  }

  checknum() {
    int nums = 0;
    for (var items in testItem) {
      var postdata = items['post'];
      for (var i = 0; i < postdata.length; i++) {
        var item = postdata[i];
        if (item.containsKey('value')) {
          if (item["value"] != "") {
            nums++;
          }
        }
        if (item['post_id'] == '4000') {
          print('计算已填项目');
          if (item['id'] != '9999') {
            if (item.containsKey('urlArr1')) {
              if (item['urlArr1'].length > 0) {
                nums++;
              }
            }
          } else {
            nums++;
          }
        }
      }
      setState(() {
        items['count'] = nums;
      });
    }
    print(nums.toString());
    print('计算已填项');
    setState(() {
      testItem = testItem;
    });
  }

  photo(item) async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image == null) return;
    // File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;
    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      // print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        checknum();
        if (item['id'] == '9999') {
          //人车合照单独处理
          print('人车合照上传图片');
          setState(() {
            item['url'] = data['url'];
            item['url2'] = data['filename'];
          });
        } else {
          List tempimg1 =
              item.containsKey("urlArr1") ? item["urlArr1"] : new List();
          List tempimg = new List();
          tempimg.add(data["filename"]);
          tempimg.add(data["url"]);
          tempimg1.add(tempimg);
          setState(() {
            item["urlArr1"] = tempimg1;
          });
        }
      }
    }, params: map);
  }

  Widget buildcontent(items) {
    List<Widget> tiles = [];
    Widget content;

    List postdata = items["post"];
    itemid = items["id"];
    // print(param);
    // print('传递数值');
    if (items["mustmodel"].toString() == "1") {
      if (itemid == "3044") {
        print('浸泡检测');
        //浸泡检测单独处理
        tiles.add(Container(
            decoration: new BoxDecoration(
              //color: Colors.white
              color: Color.fromRGBO(238, 238, 238, 1),
            ),
            child: Stack(
              children: <Widget>[
                Align(
                    alignment: Alignment.topCenter,
                    child: Container(
                      color: Colors.white,
                      width: double.infinity,
                      height: items["mustmodel"] == "1" ? 200 : 0,
                      padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
                      child: RepaintBoundary(
                        key: _globalKey,
                        child: Stack(
                          children: [
                            new Image.asset(
                              "resource/images/jiance/qinpao.png",
                              fit: BoxFit.fitHeight,
                            ),
                            Positioned(
                                top: 20,
                                left: 50,
                                right: 30,
                                height: 25,
                                child: new GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      if (line_Height1 == 3) {
                                        setState(() {
                                          items['position'] = '';
                                          line_Height2 = 1;
                                          line_Height3 = 1;
                                          line_Height1 = 1;
                                        });
                                      } else {
                                        setState(() {
                                          items['position'] = 'top';
                                          line_Height2 = 1;
                                          line_Height3 = 1;
                                          line_Height1 = 3;
                                        });
                                      }
                                    },
                                    child: new Container(
                                        height: 1,
                                        decoration: BoxDecoration(
                                            border: Border(
                                                top: BorderSide(
                                          width: line_Height1.toDouble(),
                                          color: Colors.red,
                                        )))

                                        //       child:
                                        // new Container(
                                        //   color:Colors.red,
                                        //   height: line_Height1.toDouble()

                                        // )
                                        ))),
                            Positioned(
                                top: 50,
                                left: 50,
                                right: 30,
                                height: 30,
                                child: new GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      if (line_Height2 == 3) {
                                        setState(() {
                                          items['position'] = '';
                                          line_Height2 = 1;
                                          line_Height3 = 1;
                                          line_Height1 = 1;
                                        });
                                      } else {
                                        setState(() {
                                          items['position'] = 'center';
                                          line_Height2 = 3;
                                          line_Height3 = 1;
                                          line_Height1 = 1;
                                        });
                                      }
                                    },
                                    child: new Container(
                                        height: 1,
                                        decoration: BoxDecoration(
                                            border: Border(
                                                top: BorderSide(
                                          width: line_Height2.toDouble(),
                                          color: Colors.red,
                                        )))

                                        //       child:
                                        // new Container(
                                        //   color:Colors.red,
                                        //   height: line_Height1.toDouble()

                                        // )
                                        ))),
                            Positioned(
                                top: 80,
                                left: 50,
                                right: 30,
                                height: 30,
                                child: new GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      if (line_Height3 == 3) {
                                        setState(() {
                                          items['position'] = '';
                                          line_Height2 = 1;
                                          line_Height3 = 1;
                                          line_Height1 = 1;
                                        });
                                      } else {
                                        setState(() {
                                          items['position'] = 'bottom';
                                          line_Height2 = 1;
                                          line_Height3 = 3;
                                          line_Height1 = 1;
                                        });
                                      }
                                    },
                                    child: new Container(
                                        height: 1,
                                        decoration: BoxDecoration(
                                            border: Border(
                                                top: BorderSide(
                                          width: line_Height3.toDouble(),
                                          color: Colors.red,
                                        )))

                                        //       child:
                                        // new Container(
                                        //   color:Colors.red,
                                        //   height: line_Height1.toDouble()

                                        // )
                                        )))
                            // GestureDetector(
                            //   onPanUpdate: (DragUpdateDetails details) {
                            //     //按下
                            //     RenderBox referenceBox =
                            //         context.findRenderObject();
                            //     scrollController.animateTo(350.0 + 50,
                            //         duration: new Duration(seconds: 1),
                            //         curve: Curves.ease); //开始划线是列表自动滚动
                            //     // Offset localPosition =  referenceBox.localToGlobal(Offset.zero);
                            //     var localPosition = referenceBox
                            //         .globalToLocal(details.globalPosition);
                            //     // Offset dys = [100.00,100.00];
                            //     // localPosition.dy=100.00;

                            //     //localPosition.y=localPosition.dy-64;
                            //     setState(() {
                            //       _points = new List.from(_points)
                            //         ..add(Offset(
                            //             localPosition.dx,
                            //             localPosition.dy -
                            //                 appBar.preferredSize.height -
                            //                 20));
                            //       // _points = new List.from(_points)
                            //       //   ..add(localPosition);
                            //     });
                            //   },
                            //   onPanEnd: (DragEndDetails details) =>
                            //       _points.add(null), //抬起来
                            // ),
                            // CustomPaint(painter: new SignaturePainter(_points)),
                          ],
                        ),
                      ),
                    )),
              ],
            )
            // Padding(
            //     padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
            //     child: new ListView(
            //       children: <Widget>[buildcontent()],
            //     )),
            ));
      } else if (itemid == "3077") {
        //灯光模型单独处理
        tiles.add(Container(
            color: Colors.white,
            width: double.infinity,
            height: 150,
            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
            //color: Colors.red,
            //color: Colors.red,
            child: Align(
              alignment: Alignment.topCenter,
              child: showLightProblem(itemid, postdata, 1),
            )));

        tiles.add(Container(
            color: Colors.white,
            width: double.infinity,
            height: 150,
            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
            //color: Colors.red,
            //color: Colors.red,
            child: Align(
              alignment: Alignment.topCenter,
              child: showLightBProblem(itemid, postdata, 2),
            )));
      } else {
        tiles.add(Container(
            color: Colors.white,
            width: double.infinity,
            height: 250,
            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
            //color: Colors.red,
            //color: Colors.red,
            child: Align(
              alignment: Alignment.topCenter,
              child: showProblem(itemid, postdata),
            )));
      }
    }

    int counters = 0;

    for (var i = 0; i < postdata.length; i++) {
      var item = postdata[i];
      if (item.containsKey('value')) {
        if (item["value"] != "") {
          counters++;
        }
        if (item['post_id'] == '4000') {
          print('计算已填项目');
          if (item['id'] != '9999') {
            if (item['urlArr1'].length > 0) {
              counters++;
            }
          } else {
            counters++;
          }
        }
      }
      TextEditingController textEditingController = TextEditingController();
      double height = 80;
      if (item["mustimg"] == "1") height = 270;
      if (items["id"] == "3040") {
        //漆面检测单独
        tiles.add(Padding(
            padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
            child: new GestureDetector(
                onTap: () {
                  // print('点击测量项目');
                  setState(() {
                    currentTest = item;
                    selectIndex = i;
                    // Select_Color=Colors.grey;
                  });
                },
                child: Container(
                  color: selectIndex == i
                      ? Color.fromRGBO(230, 230, 230, 1)
                      : Colors.white,
                  // decoration: new BoxDecoration(
                  // border: new Border(
                  //   //0xffe5e5e5
                  //   //bottom:BorderSide(width: 1)
                  //   )
                  //   ),
                  // height: height,
                  child: new Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      top(item),
                      center(item),
                      item.containsKey("numerical_value")
                          ? testresult(item)
                          : new Container(height: 0),
                      item.containsKey("urlArr1")
                          ? imgs(item)
                          : new Container(height: 0)
                    ],
                  ),
                ))));
      } else {
        //print(item['id']);

        if (item['id'] == '9999') {
          print('人车合照单独布局');
          //人车合照单独布局
          tiles.add(Padding(
              padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
              child: Container(
                // color: Colors.white,
                decoration: new BoxDecoration(
                    border: new Border(
                        bottom:
                            BorderSide(width: 1, color: Color(0xffe5e5e5)))),

                // height: height,
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    top(item),
                    // center(item),

                    // item.containsKey("numerical_value")? testresult(item):new Text(''),
                    item.containsKey("url")
                        ? rencheImg(item)
                        : new Container(height: 0)
                  ],
                ),
              )));
        } else {
          tiles.add(Padding(
              padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
              child: Container(
                // color: Colors.white,
                decoration: new BoxDecoration(
                    border: new Border(
                        bottom:
                            BorderSide(width: 1, color: Color(0xffe5e5e5)))),

                // height: height,
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    top(item),
                    center(item),
                    //imgs(item)

                    // item.containsKey("numerical_value")? testresult(item):new Text(''),
                    item.containsKey("urlArr1")
                        ? imgs(item)
                        : item.containsKey("url")
                            ? rencheImg(item)
                            : new Container(height: 0)
                  ],
                ),
              )));
        }
      }
    }
    items["count"] = counters.toString();

    return ExpansionTile(
      children: tiles,

      title: RichText(
          text: TextSpan(
              text: items['name'],
              style: TextStyle(fontSize: 16.0, color: Colors.black),
              children: <TextSpan>[
            TextSpan(
                text: '*',
                style: TextStyle(
                    fontSize: 18.0,
                    color: items['ismust'] == "1" ? Colors.red : Colors.white)),
            TextSpan(
                text: "（" +
                    items['count'] +
                    '/' +
                    postdata.length.toString() +
                    '）',
                style: TextStyle(fontSize: 12.0, color: Colors.red))
          ])),
      // title: Text(
      //   item["name"],
      //   style: TextStyle(
      //     color: Colors.black,
      //     fontSize: 16,
      //   ),
      // )
    );
    // content = new Column(
    //     children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
    //     //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
    //     );
    // return content;
  }

//漆膜仪检测的数值
  Widget testresult(item) {
    Widget content;
    List<Widget> tiles = [];
    print(item["testnum"]);
    // int itemnum = int.parse(item["testnum"]);
    int itemnum = item['numerical_value'].length;
    for (var i = 0; i < itemnum; i++) {
      tiles.add(
        Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 5),
          child: new Container(
            height: 30,
            width: 30,

            decoration: new BoxDecoration(
              border: new Border.all(color: Colors.red, width: 0.0), // 边色与边宽度
              color: Color(0xFF9E9E9E), // 底色
              //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
              borderRadius:
                  BorderRadius.all(Radius.circular(15.0)), // 也可控件一边圆角大小
            ),

            //color: Colors.red,
            child: new Align(
                alignment: Alignment.center,
                child: new Text(
                  item.containsKey('numerical_value')
                      ? item['numerical_value'][i].toString()
                      : '0',
                  style: TextStyle(color: Colors.white, fontSize: 10),
                )),
          ),
        ),
      );
    }
    tiles.add(
      Padding(
          padding: new EdgeInsets.fromLTRB(10, 3, 0, 5),
          child: new GestureDetector(
            onTap: () {
              setState(() {
                item['numerical_value'] = [];
              });
            },
            child: new Container(
              height: 25,
              width: 40,

              decoration: new BoxDecoration(
                border: new Border.all(color: Colors.red, width: 0.0), // 边色与边宽度
                color: Color(0xFF9E9E9E), // 底色
                //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                // 也可控件一边圆角大小
              ),

              //color: Colors.red,
              child: new Align(
                  alignment: Alignment.center,
                  child: new Text('清空', style: TextStyle(color: Colors.white))),
            ),
          )),
    );
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    return content;
  }

  //检测项最上面组件
  Widget top(item) {
    if (item["post_id"] == "3600") {
      return Padding(
          padding: new EdgeInsets.fromLTRB(15, 0, 0, 0),
          child: new Row(
            children: <Widget>[
              RichText(
                  text: TextSpan(
                      text: item["name"],
                      style: TextStyle(fontSize: 14.0, color: Colors.black),
                      children: <TextSpan>[
                    TextSpan(
                        text: '',
                        style: TextStyle(
                            fontSize: 25.0,
                            color: item["ismust"] == "5"
                                ? Colors.red
                                : Colors.white))
                  ])),
              Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                  child: new GestureDetector(
                      onTap: () {
                        FocusScope.of(context).requestFocus(FocusNode());
                        photo(item);
                      },
                      child: new Image.asset(
                        'resource/images/user/cremra.png',
                        width: 20,
                        height: 20,
                        fit: BoxFit.contain,
                      )))
            ],
          ));
    } else {
      return Padding(
          padding: new EdgeInsets.fromLTRB(15, 5, 0, 0),
          child: new Row(
            children: <Widget>[
              RichText(
                  text: TextSpan(
                      text: item["name"],
                      style: TextStyle(fontSize: 14.0, color: Colors.black),
                      children: <TextSpan>[
                    TextSpan(
                        text: '',
                        style: TextStyle(
                            fontSize: 25.0,
                            color: item["ismust"] == "5"
                                ? Colors.red
                                : Colors.white))
                  ])),
              item["post_id"] != "4000"
                  ? item["mustimg"] == "1" || item["temp_mustimg"] == "1"
                      ? Padding(
                          padding: new EdgeInsets.fromLTRB(10, 2, 0, 0),
                          child: new GestureDetector(
                              onTap: () {
                                FocusScope.of(context)
                                    .requestFocus(FocusNode());
                                photo(item);
                              },
                              child: new Image.asset(
                                'resource/images/user/cremra.png',
                                width: 20,
                                height: 20,
                                fit: BoxFit.contain,
                              )))
                      : new Text('')
                  : Padding(
                      padding: new EdgeInsets.fromLTRB(10, 2, 0, 0),
                      child: new GestureDetector(
                          onTap: () {
                            photo(item);
                          },
                          child: new Image.asset(
                            'resource/images/user/cremra.png',
                            width: 20,
                            height: 20,
                            fit: BoxFit.contain,
                          )))
            ],
          ));
    }
  }

  Widget center(item) {
    if (item["id"] == "3029") {
      //车牌
      return new GestureDetector(
          child: new Padding(
              padding: new EdgeInsets.fromLTRB(15, 10, 0, 10),
              child: new Text(item["value"])),
          onTap: () async {
            // _showBottomSheetCallback();
          });
    } else if (item["id"] == "3035") {
      //选择品牌车系
      return new GestureDetector(
          child: new Padding(
              padding: new EdgeInsets.fromLTRB(15, 10, 0, 10),
              child: new Text(item["value"])),
          onTap: () async {
            // if(cartbrand['brand_id']==""||cartype['type_id']!=""){
            //  Navigator.of(context)
            //           .push(new MaterialPageRoute(builder: (_) {
            //         return new BrandSelectRoute(cartbrand);
            //       }));
            //       setState(() {
            //         cartype['type_id']='';
            //         cartype['value']='选择车系';
            //       });
            // }else
            // if(cartbrand['brand_id']!=''){
            //   Navigator.of(context)
            //           .push(new MaterialPageRoute(builder: (_) {
            //         return new CartypeSelectRoute(
            //             cartype, cartbrand['brand_id']);
            //       }));
            // }
          });
    } else if (item["post_id"] == "3600") {
      //补充图片
      return new Padding(
        padding: new EdgeInsets.fromLTRB(3, 10, 0, 0),
        child: new TextField(
            maxLines: 3,
            controller: buchongControll,
            onChanged: (value) {
              print(value);
              setState(() {
                item['value'] = value;
                buchongControll.text = value;
              });
            },
            decoration: InputDecoration(
              hintText: '输入补充内容',
              border: OutlineInputBorder(
                borderSide: BorderSide.none,
              ),
            )),
      );
    }
    // else if(item['id']=='9000'){
    //   //人车合照
    //   return new Container(height:0);
    // }

    else {
      if (item["post_id"] != "4000") {
        if (item["item"] == "") {
          return new TextField(

              // controller: textEditingController,
              onChanged: (value) {
                print(value);
                setState(() {
                  item['value'] = value;
                });
              },
              decoration: InputDecoration(
                hintText: item.containsKey("value") ? item['value'] : '请填写相关信息',
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
              ));
        } else {
          // return Container(height:0);
          return checkBox(item);
        }
      } else {
        // return Container(height:0);
        if (item["item"] == "") {
          return new Text('');
        } else {
          return checkBox(item);
        }
      }
    }
// item["post_id"] != "4000"
//                     ? item["item"] == ""
//                         ? new TextField(

//                             // controller: textEditingController,
//                             onChanged: (value) {
//                               print(value);
//                               setState(() {
//                                 item['value'] = value;
//                               });
//                             },
//                             decoration: InputDecoration(
//                               hintText: item.containsKey("value")
//                                   ? item['value']
//                                   : '请填写相关信息',
//                               border: OutlineInputBorder(
//                                 borderSide: BorderSide.none,
//                               ),
//                             ))
//                         : checkBox(item)
//                     : item["item"] == "" ? new Text('') : checkBox(item),
  }

  Widget rencheImg(item) {
    List<Widget> tiles = [];
    tiles.add(Padding(
      padding: new EdgeInsets.fromLTRB(10, 20, 0, 10),
      child: GestureDetector(
          onTap: () {
            List temp = [
              ['', item['url']]
            ];
            print(temp);
            Navigator.of(context).push(
              NinePicture(temp, 0),
            );
          },
          child: Image.network(item['url'], width: 100, height: 100)),
    ));
    var content = new Row(children: tiles);
    return content;
  }

  Widget imgs(item) {
    // item.containsKey("urlArr1")
    //                   ? imgs(item)
    //                   : new Container(height: 0)

    List<Widget> tiles = [];
    Widget content;

    if (item.containsKey("urlArr1")) {
      List items = item["urlArr1"];
      print(items);
      for (var i = 0; i < items.length; i++) {
        List temp1 = items[i] as List;
        tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
          child: GestureDetector(
              onTap: () {
                print('点击查看图片');
                Navigator.of(context).push(
                  NinePicture(items, i),
                );
              },
              child: Image.network(temp1[1], width: 100, height: 100)),
        ));
      }
      content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    } else if (item.containsKey("url")) {
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
        child: GestureDetector(
            onTap: () {
              print('点击查看图片');
              // Navigator.of(context).push(
              //  // NinePicture(items, i),
              // );
            },
            child: Image.network(item['url'], width: 100, height: 100)),
      ));
    } else {
      tiles.add(Container(height: 0));
    }
    //content = new Row(children: tiles);

    return content;
  }

  Widget checkBox(item) {
    List<Widget> tiles = [];
    Widget content;

    List<String> items = item["item"].split(',');

    String defaultv = items[0];
    // if(this.type==2){
    if (select == false) {
      if (item.containsKey("value") == false) {
        item['value'] = defaultv;
      }
    }
    //}//车商设置选项默认值
    for (var i = 0; i < items.length; i++) {
      tiles.add(Container(
          child: Wrap(children: <Widget>[
        Padding(
            padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
            child: SizedBox(
                width: 22,
                child: Radio<String>(
                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    //当前Radio的值
                    hoverColor: Color.fromRGBO(200, 200, 200, 1),
                    focusColor: Color.fromRGBO(25, 172, 249, 1),
                    value: items[i],
                    activeColor: Color.fromRGBO(25, 172, 249, 1),
                    groupValue: item['value'],
                    // groupValue: defaultv,
                    onChanged: (value) {
                      print(item);
                      if (i != 0 && item['post_id'] != '3000') {
                        setState(() {
                          select = true;
                          // defaultv = value;
                          item['temp_mustimg'] = '1';
                        });
                      } else {
                        setState(() {
                          item['temp_mustimg'] = '0';
                        });
                      }
                      setState(() {
                        select = true;
                        // defaultv = value;
                        item['value'] = value;
                      });
                    })
                    )),

        // tiles.add(
        new GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              print('点击选项卡');
              if (i != 0) {
                setState(() {
                  select = true;
                  // defaultv = value;
                  //item['mustimg'] = '1';
                  item['temp_mustimg'] = '1';
                });
              } else {
                setState(() {
                  item['temp_mustimg'] = '0';
                });
              }
              setState(() {
                item["value"] = items[i];
              });
            },
            child: Padding(
                padding: new EdgeInsets.fromLTRB(8, 12, 15, 0),
                child: Text(items[i],
                    style: new TextStyle(
                        fontSize: 11,
                        color: Color.fromRGBO(100, 100, 100, 1)))))
      ])));
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        //  resizeToAvoidBottomPadding:resize,
        key: _scaffoldKey,
        appBar: appBar,
        body: Container(
          height: 800,
          color: Colors.white,
          child: Stack(children: <Widget>[
            loaddata
                ? Padding(
                    padding: new EdgeInsets.fromLTRB(0, 0, 0, 50),
                    child: ListView(
                      controller: scrollController,
                      children: _buildList(),
                    ))
                : new Text(''),
            Align(
                alignment: Alignment.bottomCenter,
                child: Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                    width: double.infinity,
                    color: Color.fromRGBO(27, 182, 251, 1),
                    child: new FlatButton(
                        onPressed: () {
                          // connect();
                          // subOrder(0);
                          alertfinsh();
                        },
                        child: new Text(
                          '检测完成？提交',
                          style: TextStyle(color: Colors.white),
                        )),
                  ),
                )),
          ]),
        ),
      ),
      onWillPop: () => willpop(),
    );
  }

//  Future<bool> willpop() {
//     _showDialog();
//     return Future.value(false);
//   }

  alertfinsh() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('是否已全部项目检测完成?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context, rootNavigator: true).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否，继续检测',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context, rootNavigator: true).pop();
                    subOrder(0);
                    // Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }

  //提交检测项
  subOrder(types) {
    FocusScope.of(context).requestFocus(FocusNode());
    print('订单状态');
    print(this.status);
    // if (this.orderStatus == "0"||this.orderStatus == "1") {
    Map<String, Object> map = new Map();
    map["oid"] = this.oid;
    map["type"] = this.type.toString();
    if (types == 1) {
      for (var item in testItem) {
        for (var items in item["post"]) {
          if (items["show_report"] == "是") {
            items["show_report"] = "1";
          }
          if (items["show_report"] == "否") {
            items["show_report"] = "0";
          }
        }
      }
    }
    Map chechdata1 = {"checkData": testItem};
    Map picinspects = new Map();

    for (var item in testItem) {
      if (item['id'] == '4000') {
        //照片和检测项分开
        picinspects = item;
        //testItem.remove(item);
      }
    }
    
    picinspects['post'].add(picParam); //增加人车合照

    Map checkdata = {
      "otherData": chechdata1,
      "formalities": formalities,
      'result': Checkresult,
      "pics": picinspects
    };
    if (types == 1) {
      //生成报告单时，手续信息不变
      checkdata = {
        "otherData": chechdata1,
        "formalities": oldformalities,
        'result': Checkresult,
        "pics": picinspects
      };
    }
    // checkdata["otherData"]["checkData"]=testItem;
    // map["inspector"] = jsonEncode(testItem);
    map["inspector"] = jsonEncode(checkdata);
    // print('传递的检测项');
    print(map);
    HttpHelper.post(HttpHelper.API_SubOrder, (data) async {
      if (data != null) {
        // Toast.show(data["msg"], context);
        // print('上传检测项');
        // print(data);
        if (data["code"].toString() == "1") {
          Toast.show('检测完成，可查看报告', context);

          if (connectBluetooth) {
            // flutterBlue.stopScan();
            // device.disconnect(); //退出就断开蓝牙
          }
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new PapularinspectReults(this.oid, this.type);
          }));
          // if (types == 1) {
          //   setState(() {
          //     showUrl = true;
          //   });
          // } else {
          //  // Navigator.pop(context);
          // }
        }
      }
    }, params: map);
    // }
  }

  List<Widget> _buildList() {
    List<Widget> widgets = [];
    widgets.add(buildcontents());
    for (var item in testItem) {
      widgets.add(buildcontent(item));
    }

    widgets.add(
      new Container(
          child: new Padding(
        padding: new EdgeInsets.fromLTRB(10, 10, 10, 10),
        child: TextField(
          maxLines: 5,
          onChanged: (value) {
            setState(() {
              Checkresult = value;
              resize = true;
            });
          },
          decoration: InputDecoration(
              border: InputBorder.none,
              fillColor: Color.fromRGBO(238, 238, 238, 1),
              filled: true,
              labelStyle: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),
              labelText: '输入最终检测结论'),
        ),
      )),
    );
    // this._cityNames.keys.forEach((key) {
    //   widgets.add(_item(key, _cityNames[key]));
    // });
    return widgets;
  }

  Widget _item(String city, List<String> subCities) {
    return ExpansionTile(
        children: subCities.map((subCity) => _buildSub(subCity)).toList(),
        title: Text(
          city,
          style: TextStyle(
            color: Colors.black54,
            fontSize: 20,
          ),
        ));
  }

  Widget _buildSub(String subCity) {
    return FractionallySizedBox(
      widthFactor: 1,
      child: Container(
        height: 40,
        margin: EdgeInsets.only(bottom: 5, left: 12),
        //decoration: BoxDecoration(color: Colors.grey),
        child: Text(
          subCity,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

//灯光异常图片
  Widget showLightBProblem(itemid, postdata, type) {
    // List postData = param["post"];
    String modelUrl = "resource/images/jiance/model/light/light_b.png";

    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    // if (type == 1) {
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );
    for (var i = 0; i < postdata.length; i++) {
      var item = postdata[i];
      var id = item["id"];
      List<String> items = item["item"].split(',');
      String urls = '';
      for (int n = 0; n < items.length; n++) {
        if (item["value"] == items[n]) {
          if (n == 0) continue;
          if (int.parse(id) < 4010 && int.parse(id) != 4016) continue;
          //urls = 'resource/images/jiance/model/boli/40202.png';
          urls = 'resource/images/jiance/model/light/' +
              id.toString() +
              '-' +
              n.toString() +
              '.png';
          tiles.add(
            Positioned(child: new Image.asset(urls)),
          );
        }
        print(urls);
      }
    }

    // }

    content = new Stack(children: tiles);
    return content;
  }

  //灯光异常图片
  Widget showLightProblem(itemid, postdata, type) {
    // List postData = param["post"];
    String modelUrl = "resource/images/jiance/model/light/light_f.png";

    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    // if (type == 1) {
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );
    for (var i = 0; i < postdata.length; i++) {
      var item = postdata[i];
      var id = item["id"];
      List<String> items = item["item"].split(',');
      String urls = '';
      for (int n = 0; n < items.length; n++) {
        if (item["value"] == items[n]) {
          if (n == 0) continue;

          if (int.parse(id) > 4009 && int.parse(id) != 4016) continue;
          //urls = 'resource/images/jiance/model/boli/40202.png';
          urls = 'resource/images/jiance/model/light/' +
              id.toString() +
              '-' +
              n.toString() +
              '.png';
          tiles.add(
            Positioned(child: new Image.asset(urls)),
          );
        }
        print(urls);
      }
    }

    content = new Stack(children: tiles);
    return content;
  }

  //异常图片
  Widget showProblem(itemid, postdata) {
    // List postData = param["post"];
    String modelUrl = "resource/images/jiance/carmodel2.png";
    if (itemid == "3043") {
      //结构件
      modelUrl = "resource/images/jiance/model/jiegou/jiegou.jpg";
    } else if (itemid == "3044") {
      //浸泡检测
      modelUrl = "resource/images/jiance/qinpao.png";
    } else if (itemid == "3076") {
      //车身玻璃
      modelUrl = "resource/images/jiance/model/boli/boli.png";
    }
    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );

    if (itemid != "3044") {
      //浸泡检测不需要实时图片
      // List postData = param["post"];
      for (var i = 0; i < postdata.length; i++) {
        var item = postdata[i];
        List<String> items = item["item"].split(',');

        var id = item["id"];
        // print(id);
        if (item.containsKey("value")) {
          if (item["post_id"] == "3076") {
            String urls;
            for (int n = 0; n < items.length; n++) {
              if (item["value"] == items[n]) {
                if (n == 0) continue;
                //urls = 'resource/images/jiance/model/boli/40202.png';
                urls = 'resource/images/jiance/model/boli/' +
                    id.toString() +
                    '-' +
                    n.toString() +
                    '.png';
              }
            }
            if (item["value"] != items[0]) {
              File imgs = File(urls);
              var dir_bool = imgs.exists();
              // print(dir_bool);
              //print(urls);
              tiles.add(
                Positioned(child: new Image.asset(urls)),
              );
            }
          } else {
            if (items[0] != item["value"]) {
              //有异常情况
              String urls;
              if (item["post_id"] == "3043") {
                urls = 'resource/images/jiance/model/jiegou/' +
                    id.toString() +
                    '.png';
              } else {
                //漆面检测
                for (int n = 0; n < items.length; n++) {
                  if (item["value"] == items[n]) {
                    if (n == 0) continue;
                    int tempv = 1;
                    if (n == 1) {
                      tempv = 2;
                    }
                    urls = 'resource/images/jiance/model/qimian/' +
                        id.toString() +
                        '-' +
                        tempv.toString() +
                        '.png';
                    //urls = 'resource/images/jiance/model/boli/40202.png';
                    // urls = 'resource/images/jiance/model/boli/' +
                    //     id.toString() +
                    //     '-' +
                    //     n.toString() +
                    //     '.png';
                  }
                }
                // urls = 'resource/images/jiance/model/qimian/' +
                //     id.toString() +
                //     '.png';
              }

              File imgs = File(urls);
              var dir_bool = imgs.exists();
              // print(dir_bool);
              //print(urls);
              tiles.add(
                Positioned(child: new Image.asset(urls)),
              );
            }
          }
        }
      }
    }
    content = new Stack(children: tiles);
    return content;
  }

  //手续信息单独处理
  Widget itemContent(item) {
    var child;
    if (item["type"] == "0") {
      child = Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
          child: Row(
            // crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Radio<String>(
                  //当前Radio的值
                  hoverColor: Color.fromRGBO(200, 200, 200, 1),
                  focusColor: Color.fromRGBO(25, 172, 249, 1),
                  value: "有",
                  activeColor: Color.fromRGBO(25, 172, 249, 1),
                  groupValue: item["value"],
                  // groupValue: defaultv,
                  onChanged: (value) {
                    String code = item["code"];
                    // String code = item["code"];

                    setState(() {
                      item["value"] = value;
                      formalities[code] = value;
                      // paytype = value;
                    });
                  }),
              new Text("有",
                  style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
              Radio<String>(
                  //当前Radio的值
                  hoverColor: Color.fromRGBO(200, 200, 200, 1),
                  focusColor: Color.fromRGBO(25, 172, 249, 1),
                  value: "无",
                  activeColor: Color.fromRGBO(25, 172, 249, 1),
                  groupValue: item["value"],
                  // groupValue: defaultv,
                  onChanged: (value) {
                    // String code = item["code"];
                    String code = item["code"];
                    // item["value"] = value;
                    // formalities[code] = value;
                    setState(() {
                      item["value"] = value;
                      formalities[code] = value;
                    });
                  }),
              new Text("无",
                  style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
            ],
          ));
    } else if (item["type"] == "1") {
      DateTime initialDate = DateTime.now();
      child = Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
          child: Align(
              alignment: Alignment.centerRight,
              child: new GestureDetector(
                  child: new Text(item["value"]),
                  onTap: () async {
                    final DateTime dateTime = await showDatePicker(
                      context: context,
                      //定义控件打开时默认选择日期
                      initialDate: initialDate,
                      //定义控件最早可以选择的日期
                      firstDate: DateTime(2010, 1),
                      //定义控件最晚可以选择的日期
                      lastDate: DateTime(2050, 1),
                      locale: Locale('zh'),

                      //locale: Locale.fromSubtags(languageCode: 'zh'),
                      // builder: (BuildContext context, Widget child) {
                      //   return Theme(
                      //     data: CommonColors.themData,
                      //     child: child,
                      //   );
                      // },
                    );
                    // Locale myLocale = Localizations.localeOf(context);
                    // final DateTime picker = await showDatePicker(
                    //     context: context,
                    //     initialDate: DateTime.now(),
                    //     firstDate: DateTime(2016),
                    //     lastDate: DateTime(2019),
                    //     locale: myLocale);
                    // setState(() {
                    //   item["value"] = picker.toString();
                    // });
                    if (dateTime != null) {
                      setState(() {
                        String code = item["code"];
                        print(dateTime);
                        var temp_arr = dateTime.toString().split(' ');

                        // DateTime.fromMillisecondsSinceEpoch(dateTime);
                        item["value"] = temp_arr[0];
                        // item["value"] =
                        //     formatDate(dateTime, [yyyy, "-", mm, "-", dd]);
                        formalities[code] = item["value"];
                      });
                    }
                  })));
    } else if (item["type"] == "2") {
      child = new TextField(
          onChanged: (value) {
            String code = item["code"];
            item["value"] = value;
            formalities[code] = value;
          },
          textAlign: TextAlign.right,
          //controller: _validtroller,
          decoration: InputDecoration(
              hintText: item["value"] == "" ? '请填写信息' : item["value"],
              border: OutlineInputBorder(
                borderSide: BorderSide.none,
              )));
    } else if (item["type"] == "3") {
      child = Switch(
        //当前状态
        value: item["value"] == "是" ? true : false,
        // 激活时原点颜色
        activeColor: Colors.blue,
        inactiveTrackColor: Colors.blue.shade50,
        onChanged: (value) {
          //重新构建页面
          setState(() {
            String code = item["code"];
            item["value"] = value == true ? "是" : "否";
            formalities[code] = value;
          });
        },
      );
    } else if (item["type"] == "4") {
      child = Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
          child: Align(
              alignment: Alignment.centerRight,
              child: new GestureDetector(
                  child: new Text(item["value"]),
                  onTap: () async {
                    //Navigator.pushNamed(context, 'insurance_company');
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (_) {
                      return new Insurance_Page(item);
                    }));
                  })));
    }

    if (item["type"] == "3") {
      return new Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0), child: child);
    } else {
      return Expanded(
          child: new Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 10, 0), child: child));
    }
  }

  Widget buildcontents() {
    List<Widget> tiles = [];
    Widget content;
    int counters = 0;
    for (var item in formList) {
      if (item.containsKey('value')) {
        if (item["value"] != "") {
          counters++;
        }
      }
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
          child: Container(
              color: Colors.white,
              height: 50,
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                      child: new Padding(
                          padding: new EdgeInsets.fromLTRB(15, 0, 10, 0),
                          child: Align(
                              alignment: Alignment.centerLeft,
                              child: new Text(
                                item['title'],
                                style: TextStyle(
                                    fontSize: 15,
                                    color: Color.fromRGBO(102, 102, 102, 1)),
                              )))),
                  status == "0" || status == "1"
                      ? itemContent(item)
                      : Expanded(
                          child: Padding(
                              padding: new EdgeInsets.fromLTRB(0, 0, 15, 0),
                              child: Align(
                                  alignment: Alignment.centerRight,
                                  child: new Text(item["value"]))))
                  // Expanded(
                  //   child: new Padding(
                  //       padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                  //       child: new TextField(
                  //           textAlign: TextAlign.right,
                  //           //controller: _validtroller,
                  //           decoration: InputDecoration(
                  //             hintText: '验证码',
                  //             border: OutlineInputBorder(
                  //               borderSide: BorderSide.none,
                  //             ),
                  //           ))),
                  // child: new Text(
                  //   item['sub_title'],
                  //   style:
                  //       TextStyle(fontSize: 15, color: item['sub_color']),
                  // )),
                  //)
                ],
              ))));
    }
    return ExpansionTile(
      children: tiles,
      title: RichText(
          text: TextSpan(
              text: '手续信息',
              style: TextStyle(fontSize: 16.0, color: Colors.black),
              children: <TextSpan>[
            TextSpan(
                text: '*', style: TextStyle(fontSize: 18.0, color: Colors.red)),
            TextSpan(
                text: "（" +
                    counters.toString() +
                    '/' +
                    formList.length.toString() +
                    '）',
                style: TextStyle(fontSize: 12.0, color: Colors.red))
          ])),
      // title: Text(
      //   item["name"],
      //   style: TextStyle(
      //     color: Colors.black,
      //     fontSize: 16,
      //   ),
      // )
    );
    // content = new Column(
    //     children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
    //     //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
    //     );
    // return content;
  }

//16进制转换成10进制数值
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }

  //车牌输入法
  void _showBottomSheet() {
    print('键盘出现');
    if (pwdData == "输入车牌") {
      setState(() {});
    }
    // new NumberKeyboardActionSheet(name: "1111", controller: car_num);
    setState(() {
      // disable the button  // 禁用按钮
      _showBottomSheetCallback = null;
    });

    /*
      currentState：获取具有此全局键的树中的控件状态
      showBottomSheet：显示持久性的质感设计底部面板
      解释：联系上文，_scaffoldKey是Scaffold框架状态的唯一键，因此代码大意为，
           在Scaffold框架中显示持久性的质感设计底部面板
     */
    _scaffoldKey.currentState
        .showBottomSheet<void>((BuildContext context) {
          
          /// 将自定义的密码键盘作为其child   这里将回调函数传入
          return new board. MyKeyboard(_onKeyDown, pwdData);
        })
        .closed
        .whenComplete(() {
          if (mounted) {
            setState(() {
              // re-enable the button  // 重新启用按钮
              _showBottomSheetCallback = _showBottomSheet;
            });
          }
        });
  }

  /// 密码键盘的整体回调，根据不同的按钮事件来进行相应的逻辑实现
  void _onKeyDown(board. KeyEvent data) {
    print("删除前车牌：" + pwdData);
// 如果点击了删除按钮，则将密码进行修改
    if (data.isDelete()) {
      if (pwdData != "输入车牌") {
        if (pwdData.length > 0) {
          pwdData = pwdData.substring(0, pwdData.length - 1);
          setState(() {});
        }
      }
      if (pwdData.length == 0) {
        setState(() {
          pwdData = "输入车牌";
        });
      }
    }
// 点击了确定按钮时
    else if (data.isCommit()) {
      print("点击完成");
      setState(() {
        pwdData = pwdData;
      });
      Navigator.of(context).pop();
//      if (pwdData.length != 7) {
////        Fluttertoast.showToast(msg: "密码不足6位，请重试", gravity: ToastGravity.CENTER);
//        return;
//      }
      // onAffirmButton();
    }
//点击了数字按钮时  将密码进行完整的拼接
    else {
      if (pwdData.length == 0) {}
      if (pwdData == "输入车牌") {
        setState(() {
          pwdData = "";
        });
      }
      if (pwdData.length < 8) {
        pwdData += data.key;
      }
      setState(() {
        pwdData = pwdData;
      });
    }
  }

  Future<bool> willpop() {
    print('退出');
    if (connectBluetooth) {
      // flutterBlue.stopScan();
      // device.disconnect(); //退出就断开蓝牙
    }
    return Future.value(true);
    // _showDialog();
    //  return Future.value(false);
  }

  _showDialog() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('此项是否已经检测完毕?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否，继续检测',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: CachedNetworkImage(
                  imageUrl: widget.picList[index][1],
                  fit: BoxFit.cover,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                  widget.picList.length,
                  (i) => GestureDetector(
                    child: CircleAvatar(
                      foregroundColor: Theme.of(context).primaryColor,
                      radius: 8.0,
                      backgroundColor: index == i
                          ? Theme.of(context).primaryColor
                          : Colors.white,
                    ),
                    onTap: () {
                      setState(() {
                        startX = endX = 0;
                        index = i;
                      });
                    },
                  ),
                ).toList(),
              ),
            )
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }

  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}

class SignaturePainter extends CustomPainter {
  SignaturePainter(this.points);

  final List<Offset> points; // Offset:一个不可变的2D浮点偏移。

  void paint(Canvas canvas, Size size) {
    Paint paint = new Paint() //设置笔的属性
      ..color = Colors.red[800]
      ..strokeCap = StrokeCap.round
      ..isAntiAlias = true
      ..strokeWidth = 2.0
      ..strokeJoin = StrokeJoin.bevel;

    for (int i = 0; i < points.length - 1; i++) {
      //画线
      if (points[i] != null && points[i + 1] != null)
        canvas.drawLine(points[i], points[i + 1],
            paint); //drawLine(Offset p1, Offset p2, Paint paint) → void
//      canvas.drawOval(
//          new Rect.fromCircle(center: points[i], radius: 20.0), paint);
////      canvas.drawOval(rect, paint)
//    canvas.drawCircle(points[i], 20.0, paint);
    }
  }

  /**
   * 是否重绘
   */
  bool shouldRepaint(SignaturePainter other) => other.points != points;
//  bool shouldRepaint(SignaturePainter other) =>true;
}
